package com.menker.app.common;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.hannesdorfmann.mosby3.mvp.MvpPresenter;
import com.hannesdorfmann.mosby3.mvp.MvpView;
import com.menker.app.Constants;
import com.menker.app.R;
import com.menker.app.webview.WebViewManager;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import myandroid.library.util.ApplicationHelper;

/**
 * @author J.Huang
 * @version 1.0
 */
public abstract class BaseWebViewToolbarActivity<V extends MvpView, P extends MvpPresenter<V>>
        extends BaseToolbarActivity<V, P> {

    protected BridgeWebView mWebView;
    protected RelativeLayout mRLayoutWebView;
    protected RefreshLayout mRefreshLayout;

    protected LinearLayout mLayoutWebView;
    protected WebViewManager mWebViewManager;

    private List<String> mToolbarTitles = new ArrayList<>();

    private OnRequestPermissionListener mOnRequestPermissionListener;
    private String mNoPermissionMsg;
    private int mPermissionCode;

    public interface OnRequestPermissionListener {
        void onSuccess();
    }

    private NormalDialog mPermissionDialog;

    protected void setupUI(ToolbarOwner.IToolbar iToolbar) {
        super.setupUI(iToolbar);
        mWebView = new BridgeWebView(this.getParent() == null ? this : this.getParent());

        mWebViewManager = new WebViewManager(this, this, mWebView);
        mWebViewManager.init();

        mLayoutWebView = (LinearLayout) findViewById(R.id.activity_general_webview_layout_webview);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        );
//        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE,null);

        mLayoutWebView.addView(mWebView, 0, layoutParams);
    }

    public void initCustomUI() {
        mRefreshLayout = (RefreshLayout) findViewById(R.id.activity_general_webview_refresh_layout);

        if (mRefreshLayout != null) {
            mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    refreshlayout.finishRefresh(1000);
                    mWebViewManager.reload();
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mWebViewManager != null) {
            mWebViewManager.resume();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mWebViewManager != null) {
            mWebViewManager.start();
        }
    }

    @Override
    public void onPause() {
        if (mWebViewManager != null) {
            mWebViewManager.pause();
        }
        super.onPause();
    }

    @Override
    public void onStop() {
        if (mWebViewManager != null) {
            mWebViewManager.stop();
        }
        super.onStop();
    }

    @Override
    public void onDestroy() {
        mToolbar = null;
        mToolbarTitle = null;
        mToolbarOwner = null;

        if (mLayoutWebView != null) {
            mLayoutWebView.removeAllViews();
        }

        // mWebViewManager有this的引用，必须清空
        if (mWebViewManager != null) {
            mWebViewManager.destroy();
            mWebViewManager = null;
        }

        if (mActionBarMenuActionList != null) {
            mActionBarMenuActionList.clear();
        }

        if (mPermissionDialog != null) {
            mPermissionDialog.superDismiss();
            mPermissionDialog = null;
        }

        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        }

        switch (resultCode) {
            case Constants.ACTIVITY_CODE.RESULT_REFRESH:
                if (Utils.Network.isNetworkAvailable() && mWebViewManager != null) {
                    mWebViewManager.reload();
                } else {
                    Utils.UI.showToastShort(getString(R.string.error_no_internet));
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == mPermissionCode) {
            boolean granted = true;
            for (int i : grantResults) {
                if (i != PackageManager.PERMISSION_GRANTED) {
                    granted = false;
                    break;
                }
            }

            if (mOnRequestPermissionListener != null) {
                if (!granted) {
                    // 没有获取到权限，做特殊处理

                    if (mPermissionDialog != null) {
                        Utils.UI.showToastLong(mNoPermissionMsg);
                        return;
                    }

                    mPermissionDialog = new NormalDialog(this);

                    mPermissionDialog.isTitleShow(false)
                            .btnNum(1)
                            .bgColor(Color.parseColor("#FFFFFF"))
                            .cornerRadius(5)
                            .content(mNoPermissionMsg)
                            .contentGravity(Gravity.CENTER)
                            .contentTextSize(13)
                            .contentTextColor(Color.parseColor("#333333"))
                            .dividerColor(Color.parseColor("#CCCCCC"))
                            .btnText("确定")
                            .btnTextSize(15.5f)
                            .btnTextColor(Color.parseColor("#0092FF"))
                            .widthScale(0.7f)
                            .show();

                    mPermissionDialog.setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            mPermissionDialog.superDismiss();
                            mPermissionDialog = null;
                        }
                    });
                } else {
                    mOnRequestPermissionListener.onSuccess();
                }
            }
        }
    }

    public void setOnRequestPermissionListener(OnRequestPermissionListener onRequestPermissionListener,
                                               String noPermissionMsg,
                                               int permissionCode) {
        mOnRequestPermissionListener = onRequestPermissionListener;
        mNoPermissionMsg = noPermissionMsg;
        mPermissionCode = permissionCode;
    }

    public void setEnableRefresh(boolean enable) {
        if (mRefreshLayout == null) return;

        mRefreshLayout.setEnableRefresh(enable);
    }
}
